package com.itheima.aspect;

import cn.hutool.core.util.ObjectUtil;
import com.itheima.dto.LoginRequest;
import com.itheima.mapper.LoginLogMapper;
import com.itheima.pojo.LoginLog;
import com.itheima.vo.UserInfoVo;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Aspect
@Component
public class LoginLogAspect {

    @Autowired
    private LoginLogMapper loginLogMapper;


    @Around("execution(* com.itheima.service.impl.LoginServiceImpl.login(..)))")
    public Object recordLoginLog(ProceedingJoinPoint joinPoint) throws Throwable {


        Object[] args = joinPoint.getArgs();

        LoginRequest loginRequest = (LoginRequest) args[0];
        //获取用户名
        String username = loginRequest.getUsername();
        //获取密码
        String password = loginRequest.getPassword();

        //操作时间
        LocalDateTime time = LocalDateTime.now();

        long begin = System.currentTimeMillis();
        Object result = joinPoint.proceed();
        UserInfoVo userInfoVo = (UserInfoVo) result;
        Integer isSuccess;
        //获取jwt令牌
        String token = userInfoVo.getToken();
        if (ObjectUtil.isEmpty(result)) {
            isSuccess = 0;
            token = null;
        } else {
            isSuccess = 1;
        }

        long end = System.currentTimeMillis();
        //获取操作耗时
        Long costTime = end - begin;


        LoginLog loginLog = new LoginLog(null, username, password, time, isSuccess, token, costTime);
        loginLogMapper.insert(loginLog);

        return result;


    }

}
